<!doctype html>
<html>
<head>
  <meta charset="utf-8"/>
  <meta http-equiv="X-UA-Compatible" content="IE=7; IE=EmulateIE9; IE=10" />
  <meta name="keywords" content="setUpKMLManager,setUpMouseOverListener,loadChoroplethMap,parseXml,onParsed" />
  <title>HERE Maps API Example: Choropleth Map</title>
  <!-- Set up constants such as APP ID and token -->
  <script type="text/javascript" src="../libs/hereAppIdAndToken.js"></script>
  <!-- Bootstrap jQuery Library -->
  <script type="text/javascript" src="../libs/jQl.min.js"></script>
  <!-- Asynchronously the HERE Maps API for JavaScript -->
  <script type="text/javascript" src="../libs/hereAsyncLoader.js"
    id="HereMapsLoaderScript"
    data-map-container="mapContainer"
    data-params="maps,datarendering"
    data-callback="afterHereMapLoad" >
  </script>
  <link rel="icon" href="http://here.com/favicon.ico"/>
  <!--<link href="http://developer.here.com/html/css/main.css" rel="stylesheet" />-->
</head>
<body>
  <h1>Choropleth Map : Accession Dates to the European Union</h1>
  <p>
  	Hover over the map to find the accession dates of the EU States.
  	The outline of the each state is loaded from a KML file, the color is
  	altered  prior to creating the map. Darker colored countries joined the group
  	earlier than lighter colored countries.
  </p>
  <div id="mapContainer" style="width:540px; height:334px;"></div>
<script id="example-code" data-categories="events" type="text/javascript" >
//<![CDATA[

// Get the DOM node to which we will append the map
var map,
  infobubbles;

function setUpMouseOverListener(map) {
  map.addListener("mouseover", function (evt) {
    var objects = map.getObjectsAt(evt.targetX, evt.targetY),
      object,
      i;

    for (i = 0; i < objects.length; i += 1) {
      object = objects[i];
      if (object instanceof nokia.maps.map.Polygon) {
        object.dispatch(new nokia.maps.dom.Event({type: "click", target: object}));
        evt.stopImmediatePropagation();
      }
    }
  });
}


function arrayToHashTable(rows) {
  var hashTable = {},
    i,
    fields;

  hashTable.data = {};
  hashTable.key = rows[0][0];
  hashTable.value = rows[0][1];
  hashTable.minValue = rows[1][1];
  hashTable.maxValue = rows[1][1];

  // Start from 1 since we have a header row.
  for (i = 1; i < rows.length; i += 1) {
    fields = rows[i];
    hashTable.data[fields[0]] = fields[1];
    hashTable.minValue = Math.min(hashTable.minValue,  fields[1]);
    hashTable.maxValue  =  Math.max(hashTable.maxValue,  fields[1]);
  }

  hashTable.getItem = function (in_key) {
    return this.data[in_key];
  };
  hashTable.hasItem = function (in_key) {
    return typeof (this.data[in_key]) !== 'undefined';
  };

  hashTable.getColor = function (minColor, maxColor, in_key) {
    var hexMinColor = parseInt(minColor, 16),
      hexMaxColor = parseInt(maxColor, 16),
      color = hexMinColor + Math.round(((hexMaxColor -  hexMinColor) *
        (this.data[in_key] - this.minValue) / (this.maxValue - this.minValue))),
      hexColor = color.toString(16);
    return hexColor;
  };


  return hashTable;
}



var kml,
  resultSet,
  container,
  data;


// We define a callback function for parsing kml file,
// and then push the parsing result to map display
function onParsed(kmlManager) {
  var boundingBox;

  // KML file was successfully loaded
  if (kmlManager.state === "finished") {

    // KML file was successfully parsed
    resultSet = new nokia.maps.kml.component.KMLResultSet(kmlManager.kmlDocument, map);
    resultSet.addObserver("state", function (resultSet) {
      if (resultSet.state === "finished") {
        // Retrieve map objects container from KML resultSet
        container = resultSet.container;
        boundingBox = container.getBoundingBox();
        if (boundingBox) {
          // Switch the viewport of the map to show all KML map objects within the container
          map.zoomTo(boundingBox);
        }
      }
    });

    // Add the container to the map's object collection so it will be rendered onto the map.
    container = resultSet.create();
    map.objects.add(container);
  }
}


function err() {
  alert("An Error has occurred.");
}

function parseXml(xml) {
  $(xml).find("Placemark").each(function () {
    var countryName = $(this).children("name").text(),
      accessionDate,
      newDescNode  = document.createElement('description'),
      colorNode  = document.createElementNS('', 'color'),
      polyStyleNode  = document.createElementNS('', 'PolyStyle'),
      styleNode  = document.createElementNS('', 'Style'),
      newColor;

    if (data.hasItem(countryName) === false) {
      $(this).remove();
    } else {
      accessionDate = data.getItem(countryName);
      // Update the description since the KML PlaceMark already has one.
      newDescNode.appendChild(document.createTextNode("Joined in " + accessionDate));
      $(this).children("description").replaceWith(newDescNode);

      /**
       * ColorSyle is in ABGR format, fix the opacity to 66 ,the blue part to FF
       * and the red part to 00  but allow a range for the green based on the data.
       */
      newColor = "66bb" + data.getColor("11", "ff", countryName) + "00";
      colorNode.appendChild(document.createTextNode(newColor));
      polyStyleNode.appendChild(colorNode);
      styleNode.appendChild(polyStyleNode);
      $(styleNode).appendTo(this);
    }
  });

  var doc =  xml.getElementsByTagName('Document')[0];
  kml.parse(doc);
}

function setUpKMLManager(){
  kml = new nokia.maps.kml.Manager();
  // Add an observer to kml manager
  kml.addObserver("state", onParsed);
}

function loadChoroplethMap(){
  data = arrayToHashTable([
    ['Country', 'Date'],
    ['France', 1952],
    ['Germany', 1952],
    ['Italy', 1952],
    ['Belgium', 1952],
    ['Netherlands', 1952],
    ['Luxembourg', 1952],
    ['Ireland', 1973],
    ['United Kingdom', 1973],
    ['Denmark', 1973],
    ['Greece', 1981],
    ['Spain', 1986],
    ['Portugal', 1986],
    ['Austria', 1995],
    ['Sweden', 1995],
    ['Finland', 1995],
    ['Cyprus', 2004],
    ['Malta', 2004],
    ['Hungary', 2004],
    ['Poland', 2004],
    ['Slovakia', 2004],
    ['Latvia', 2004],
    ['Estonia', 2004],
    ['Lithuania', 2004],
    ['Czech Republic', 2004],
    ['Slovenia', 2004],
    ['Bulgaria', 2007],
    ['Romania', 2007],
    ['Croatia', 2013]
  ]);
  
  $.ajax({
    type: "GET",
    url: "./kml/europe.kml",
    dataType: "xml",
    success: parseXml,
    error : err
  });
}

function afterHereMapLoad(theMap) {
  map = theMap;
  setUpMouseOverListener(map);
  infoBubbles = new nokia.maps.map.component.InfoBubbles();
  setUpKMLManager();
  
  container = new nokia.maps.map.Container();
  map.components.add(infoBubbles);
  
  loadChoroplethMap();
 
}
//]]>
</script>
<script type="text/javascript" src="../libs/prettyprint.js"></script>
</body>
</html>